import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yn_goods/base/widget/base_list_more_get_builder.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/pages/model_home.dart';
import 'package:flutter_yn_goods/pages/search/model/search_product_model.dart';
import 'package:flutter_yn_goods/utils/utils_other.dart';
import 'package:flutter_yn_goods/widgets/appbar/common_app_bar.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'search_logic.dart';

class SearchPage extends StatelessWidget {
  final logic = Get.put(SearchLogic());

  @override
  Widget build(BuildContext context) {
    return BaseListMoreGetBuilder<SearchLogic>(
      appBar: _buildAppBar(),
      headerBuilder: (logic) {
        return _buildHistoryView();
      },
      builder: (logic) {
        // SliverList.separated(itemBuilder: itemBuilder, separatorBuilder: separatorBuilder)
        return SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          sliver: SliverList.separated(
            // padding: EdgeInsets.all(16.w),
            itemCount: logic.list.length,
            separatorBuilder: (_, __) =>
                Divider(height: 1.w, color: AppColor.colorE5E5E5),
            itemBuilder: (context, index) {
              ModelHomeList item = logic.list[index];
              return _buildProductItem(item);
            },
          ),
        );
      },
    );

    // return Scaffold(
    //   backgroundColor: Colors.white,
    //   appBar: _buildAppBar(),
    //   body: Obx(() => logic.showResult.value ? _buildSearchResults() : _buildHistoryView()),
    // );
  }

  // 构建AppBar，包含搜索框
  PreferredSizeWidget _buildAppBar() {
    return CommonAppBar(
      title: LocaleKeys.search.tr,
      titleWidget: Hero(
        tag: 'search_bar',
        child: Container(
          height: 36.w,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: AppColor.colorF5F5F5,
            borderRadius: BorderRadius.circular(18.w),
          ),
          child: TextField(
            controller: logic.searchController,
            textInputAction: TextInputAction.search,
            onSubmitted: (_) => logic.onSearch(),
            decoration: InputDecoration(
              contentPadding:
                  EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
              isCollapsed: true,
              hintText: LocaleKeys.search_placeholder.tr,
              hintStyle: TextStyle(
                color: AppColor.color999999,
                fontSize: 14.sp,
              ),
              border: InputBorder.none,
              suffixIcon: IconButton(
                icon: Icon(
                  Icons.search,
                  color: AppColor.color999999,
                  size: 20.w,
                ),
                onPressed: logic.onSearch,
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 构建搜索历史视图
  Widget _buildHistoryView() {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 搜索历史标题栏
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                LocaleKeys.search_history.tr,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: AppColor.color282828,
                ),
              ),
              if (logic.searchHistory.isNotEmpty)
                GestureDetector(
                  onTap: logic.clearSearchHistory,
                  child: Text(
                    LocaleKeys.clear_history.tr,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: AppColor.color999999,
                    ),
                  ),
                ),
            ],
          ),
          SizedBox(height: 16.w),
          // 搜索历史内容
          Obx(() => Wrap(
                spacing: 12.w,
                runSpacing: 12.w,
                children: logic.searchHistory
                    .map((item) => _buildHistoryItem(item))
                    .toList(),
              )),
        ],
      ),
    );
  }

  // 构建历史记录项
  Widget _buildHistoryItem(String text) {
    return GestureDetector(
      onTap: () => logic.onHistoryItemTap(text),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.w),
        decoration: BoxDecoration(
          color: AppColor.colorF5F5F5,
          borderRadius: BorderRadius.circular(16.w),
        ),
        child: Text(
          text,
          style: TextStyle(
            fontSize: 14.sp,
            color: AppColor.color666666,
          ),
        ),
      ),
    );
  }

  // 构建商品项
  Widget _buildProductItem(ModelHomeList item) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          AppRoutes.goodsInfoPage,
          arguments: {'id': item.id},
        );
      },
      behavior: HitTestBehavior.opaque,
      child: Padding(
        padding: EdgeInsets.symmetric(vertical: 12.w),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品图片
            ClipRRect(
              borderRadius: BorderRadius.circular(8.w),
              child: ImageView(
                imageUrl: item.image,
                width: 80.w,
                height: 80.w,
                fit: BoxFit.cover,
              ),
            ),
            SizedBox(width: 12.w),
            // 商品信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 商品名称
                  Text(
                    item.storeName ?? '',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 15.sp,
                      fontWeight: FontWeight.w500,
                      color: AppColor.color282828,
                    ),
                  ),
                  SizedBox(height: 8.w),
                  // 商品价格和销量
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text(
                        UtilsOther.getGoodsPrice(item.price),
                        style: TextStyle(
                          fontSize: 16.sp,
                          fontWeight: FontWeight.bold,
                          color: Colors.red,
                        ),
                      ),
                      if (item.otPrice != null &&
                          item.otPrice!.isNotEmpty &&
                          item.otPrice != '0.00')
                        Padding(
                          padding: EdgeInsets.only(left: 8.w),
                          child: Text(
                            '¥${item.otPrice}',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: AppColor.color999999,
                              decoration: TextDecoration.lineThrough,
                            ),
                          ),
                        ),
                      Spacer(),
                      Text(
                        '${item.sales ?? 0}人购买',
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: AppColor.color999999,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
